/*###########################################################
# © 2013-2016 Daniel 'grindhold' Brendle
#
# This file is part of Nostril.
#
# Nostril is free software: you can redistribute it and/or 
# modify it under the terms of the GNU Affero General Public License 
# as published by the Free Software Foundation, either 
# version 3 of the License, or (at your option) any later 
# version.
#
# Nostril is distributed in the hope that it will be 
# useful, but WITHOUT ANY WARRANTY; without even the implied 
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
# PURPOSE. See the GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public 
# License along with Nostril. 
# If not, see http://www.gnu.org/licenses/.
###########################################################*/

using Gtk;

namespace nostril {
    namespace gui {
        public class HexViewer : Viewer {
            private Gtk.Builder builder = null;
            private Gtk.TextBuffer buffer = null;
            private Gtk.Widget mainbox = null;

            public HexViewer(){
                this.builder = new Gtk.Builder();
                try {
                    this.builder.add_from_file(Main.DATAPATH+"ui/hex_viewer.ui");
                } catch (Error e){
                    stderr.printf(e.message);
                    stderr.printf("Could not load UI file %s - File not found\n",Main.DATAPATH+"ui/hex_viewer.ui");
                }

                this.buffer = this.builder.get_object("buffer") as Gtk.TextBuffer;
                this.mainbox = this.builder.get_object("mainbox") as Gtk.Widget;

                this.mainbox.show_all();
            }

            public static ViewerType get_viewer_type(){
                return ViewerType.BOTH;
            }

            private string hexdump(uint8[] data){
                string ret = "";
                for (uint i = 0; i < data.length; i++){
                    if (i % 8  == 0 && i > 0)
                        ret += " ";
                    if (i % 16 == 0 && i > 0)
                        ret += "\n";
                    ret += " %02X".printf(data[i]);
                }
                return ret;
            }

            public override void render(uint8[] data){
                this.buffer.set_text(this.hexdump(data));
            }

            public override Gtk.Widget get_responsible_widget(){
                return this.mainbox;
            }


        }
    }
}
